# -*- coding: utf-8 -*-

import Core
import Extern

_local_frame = {}
_frame_stack = []
_pragma_list = {}

def __Include(__external):
    global _local_frame, _frame_stack
    _frame_stack.append([__external, []])
    exec open(__external) in _local_frame
    _local_frame.update(locals())
    ext, pragmas = _frame_stack.pop(-1)
    _pragma_list[ext] = pragmas

def __Pragma(*args):
    _frame_stack[len(_frame_stack)-1][1].append(args)


def reset_frame(frame={}):
    global _local_frame
    _local_frame = frame
    return _local_frame

RegisterListener = Core.RegisterListener

class ModuleRegister(RegisterListener):
    def __init__(self):
        Core.RegisterListener.__init__(self)
        self.registered_modules = []

    def registerModule(self, mod):
        if len(_frame_stack) == 1:
            self.registered_modules.append(mod)

    def registerTypedef(self, tydf):
        if len(_frame_stack) != 1:
            return
#        global _local_frame
#        _local_frame[tydf.id] = tydf


def load_didl(didl_path):
    Core.set_include_handler(__Include)
    Core.set_pragma_handler(__Pragma)

    global _frame_stack
    _frame_stack = [[didl_path, []]]

    listener = ModuleRegister()
    Core.set_register_listener(listener)

#    print "before", dir(locals())
    # Execute on the current frame
    exec open(didl_path) in reset_frame(Extern.__dict__.copy())
#    print "after", dir(locals())

    return (listener.registered_modules, _frame_stack[0][1])
